home *** CD-ROM | disk | FTP | other *** search
- Path: nntp.teleport.com!usenet
- From: GHouck <hksys@teleport.com>
- Newsgroups: comp.lang.c
- Subject: Re: Union type
- Date: 11 Apr 1996 20:52:14 GMT
- Organization: systems hk
- Message-ID: <4kjrdu$3ij@nadine.teleport.com>
- References: <4kh43f$h4f@dewey.csun.edu>
- NNTP-Posting-Host: ip-pdx09-42.teleport.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.22 (Windows; I; 32bit)
-
- kc44097@csun.edu (chen) wrote:
-
- >union {
- > int integer;
- > float floating;
- >} myUnion;
- >
- > myUnion.integer = 1;
- > printf("The value of integer is %d\n", myUnion.integer);
- > printf("The value of floating is %f\n\n", myUnion.floating);
- > printf("The value of \"cast\" is %f\n", (float) myUnion.integer);
- > printf("The value of \"magic\" is %f\n\n", myUnion.integer);
- > printf("The meaning of life ``%d''\n", (int) myUnion.floating);
- > return (0);
- > The value of integer is 1
- > The value of floating is 0.000000
- > The value of cast is 1.000000
- > The value of magic is 0.000000
- > The meaning of life ``0''
- >
- > My question is : Why myUnion.integer is 1 but myUnion.floating is
- > 0.000000;Why myUnion.integer change to 0.000000 in 4th printf(),
- > and why myUnion.floating is 0 in 5th printf()?
-
- You have to realize that a union of two or more variables shares a common
- memory area; there is no conversion between the various types. So, the
- moment you placed a 1 into 'myUnion.integer', you invalidated the floating
- point value. The bit-pattern stored at the location of 'myUnion.integer'
- is the bit-pattern for an integer 1. That pattern (normally) makes no
- sense as a floating point number; therefore, the 0.0000's you are getting
- (although it could have been some other garbage number).
-
- Also, in your printf's you have to remember to print integers with '%d'
- or '%ld' formats, and double/floats with '%f' or '%lf' or '%g' formats.
- Don't mix them. That is, you cannot printf a float with a '%d' format
- specifier, and vice versa, unless you are trying to perform some sort of
- trick.
-
- Yours, Geoff Houck
-
-
-